# -*- coding:utf-8 -*-
"""
@Time : 2025/02/03 21:54 PM
@Author: xiaomi
@Des: 认证
"""

from core.Auth import create_access_token
from fastapi.security.oauth2 import OAuth2PasswordRequestForm
from fastapi import Depends, HTTPException, status
from models.base import Admin
from core.Utils import check_password

async def authorize(data: OAuth2PasswordRequestForm = Depends()):
    # 验证用户是否存在
    admin_data = await Admin.get_or_none(adminname=data.username)
    if not admin_data:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail=f"用户{data.username}密码验证失败!",
            headers={"WWW-Authenticate": "Bearer"},
        )
    if not admin_data.password:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail=f"用户{data.username}密码验证失败!",
            headers={"WWW-Authenticate": "Bearer"},
        )
    if not check_password(data.password, admin_data.password):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail=f"用户{data.username}密码验证失败!",
            headers={"WWW-Authenticate": "Bearer"},
        )
    if not admin_data.admin_status:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail=f"用户{data.username}已被管理员禁用!",
            headers={"WWW-Authenticate": "Bearer"},
        )
    access_token = create_access_token(data={"admin_id": admin_data.id, "admin_type": admin_data.admin_type})
    return {"access_token": access_token, "token_type": "bearer"}
